package ks.server.controllers.commands.admin.icon;

import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.framework.interfaces.IProcessMessage;
import ks.server.ipc.Listener;
import ks.server.persist.PersistentIconManager;
import ks.server.persist.PersistentUserManager;
import ks.server.ServerContext;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

/**
 * Process command to delete an icon.
 * 
 * @author Christopher Page
 */
public class IconDeleteController implements IProcessMessage {

	/** Primary agent to whom we can communicate our messages. */
	Communicator com;
	
	public IconDeleteController (Communicator com) {
		this.com = com;
	}
	
	/**
	 * Process the message
	 * 
	 * @param m The message to process.
	 * @return A boolean value.
	 */
	public boolean process(Message m) {
		
		PersistentUserManager um = ServerContext.getUserManager();

		if (um.getUser(m.getOriginator()) == null) {
			Message r = Listener.nack(m, 4, "Unable to delete icon: what!? I don't even..."); 
			r.setRecipient(m.getOriginator());
	        com.distribute(r);
	        return false;
		}
		if (!um.getUser(m.getOriginator()).isAdmin()) {
			Message r = Listener.nack(m, 4, "Unable to delete icon: access denied."); 
			r.setRecipient(m.getOriginator());
	        com.distribute(r);
			return false;
		}
		
		PersistentIconManager im = ServerContext.getIconManager();
		
		Node iconDelete = m.contents();
		
		if (iconDelete == null) {
			Message r = Listener.nack(m, 4, "Unable to delete icon: unknown.");
			System.err.println("[IconDeleteController] Error: null node provided.");
			r.setRecipient(m.getOriginator());
	        com.distribute(r);
			return false;
		}
		if (!iconDelete.getNodeName().equalsIgnoreCase("icon-delete")) {
			Message r = Listener.nack(m, 4, "Unable to delete icon: unknown.");
			System.err.println("[IconDeleteController] Error: node provided has value of " + iconDelete.getNodeName() + ".");
			r.setRecipient(m.getOriginator());
	        com.distribute(r);
			return false;
		}
		
		NamedNodeMap nnp = iconDelete.getAttributes();
		
		Node iconNode = nnp.getNamedItem("icon");
		
		if (iconNode == null){
			Message r = Listener.nack(m, 4, "iconNode null");
			r.setRecipient(m.getOriginator());
	        com.distribute(r);
			System.err.println("[IconDeleteController] Error: no icon attribute.");
			return false;
		}
		
		if (!im.remove(iconNode.getNodeValue())) {
			Message r = Listener.nack(m, 4, "Error: icon does not exist.");
			r.setRecipient(m.getOriginator());
	        com.distribute(r);
			System.err.println("[IconDeleteController] Error: could not remove icon.");
			return false;
		}
		
		Message r = Listener.ack(m, "Success");
        r.setRecipient(m.getOriginator());
        r.setBroadcast();
        
        com.distribute(r);
		return true;
	}
}
